package com.xy.csdn.cfg;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.apache.http.client.HttpClient;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.ExtractingResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * RestTemplate用于同步client端的核心类，简化了与http服务的通信，并满足RestFul原则，程序代码可以给它提供URL，并提取结果
 * 默认情况下，RestTemplate默认使用jdk提供http链接的能力（HttpURLConnection）
 * 可以通过setRequestFactory属性切换到不同的HTTP源，Apache HttpComponents,Netty和OkHttp。
 * @author chuanjieyang
 * @since May 22, 2019 15:34:58 PM
 */
@Configuration
public class SpringRestTemplateConfig {


    /*
        HttpMessageConverter对象转换器
        ClientHttpRequestFactory  默认是jdk的HttpURLConnection
        ResponseErrorHandler 异常处理
        ClientHttpRequestInterceptor 请求拦截器
     */

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder,HttpClient httpClient){
        RestTemplate restTemplate = builder
                .errorHandler(new CustomErrorHandler())
                .basicAuthentication("ycj","123")
                .interceptors(new CustomInterceptor())//可以添加多个，可以是多参，也可以集合
                .build();
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
        restTemplate.getMessageConverters().add(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        System.out.println(messageConverters);
        return restTemplate;
    }
}
